package com.mijie.homi.ns.traffic.receptor;

import net.sf.json.JSONObject;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.CategoryCode;
import com.mijie.homi.common.constant.TypeCode;
import com.mijie.homi.common.domain.chat.ChatMessage;
import com.mijie.homi.common.domain.session.Session;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.protocol.HomiProtocol;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.ns.core.HomiServer;
import com.mijie.homi.ns.service.ChatService;
import com.mijie.homi.ns.service.NotifyService;
import com.mijie.homi.ns.service.SessionService;
import com.mijie.homi.ns.service.UserService;

@Service
public class ChatMessageReceptor implements Receptor {

	@Autowired
	private ChatService chatService;
	@Autowired
	private UserService userService;
	@Autowired
	private SessionService sessionService;
	@Autowired
	private NotifyService notifyService;
	@Autowired
	private HomiServer homiServer;
	
	@Override
	public boolean accept(short type) {
		return type==TypeCode.MESSAGE_ROUTER_TYPE_CHAT;
	}

	
	@Override
	public void process(int receiver,short type,JSONObject originalPack){
		if(originalPack.containsKey("category")){
			int category = originalPack.getInt("category");
			if(category==CategoryCode.CHAT_VOICE || 
				category==CategoryCode.CHAT_TEXT_MESSAGE){
				Session session = sessionService.getSessionByUserId(receiver);
				if(session!=null){
					IoSession ioSession = homiServer.getIoSessionByUserId(receiver);
					if(ioSession!=null){
						HomiProtocol protocol = new HomiProtocol(TypeCode.CHAT);
						protocol.setContent(originalPack.toString());
						ioSession.write(protocol);
					}
				}else{
					User user = userService.getUserById(originalPack.getInt("sender"));
					if(user!=null){
						ChatMessage cm = new ChatMessage();
						cm.setCategory((short) originalPack.getInt("category"));
						cm.setReceiver(receiver);
						cm.setMessage(originalPack.getString("message"));
						cm.setSmallImage(originalPack.getString("smallImage"));
						notifyService.addToPushQueue(HomiUtil.makeChatPushMessage(cm,user));
					}
				}
			}
		}
	}

}
